package com.yt.app.provider.service.impl;

import com.yt.app.core.interfaces.CacheService;
import com.yt.app.core.model.Cache;
import com.yt.app.provider.dao.CacheDao;
import com.yt.core.dao.filter.DynamicSQLFilterImpl;
import com.yt.core.dao.filter.QueryFilter;
import com.yt.core.service.GenericServiceImpl;

import java.util.List;

public class CacheServiceImpl extends GenericServiceImpl<Cache, Long> implements CacheService {
	private CacheDao dao;

	public CacheServiceImpl() {
	}

	public CacheServiceImpl(CacheDao dao) {
		super(dao);
		this.dao = dao;
	}

	@Override
	public Cache getCache(String key) {
		QueryFilter filter = new DynamicSQLFilterImpl();
		filter.addFilter("Q_`key`_S_EQ", key);
		List<Cache> list = this.dao.find(filter);

		if(list != null && !list.isEmpty()){
			return list.get(0);
		}
		return null;
	}

	public void putCache(String key, String value, Long expire){
		Cache cache = getCache(key);
		if(cache == null){
			cache = new Cache();
			cache.setKey(key);
			cache.setValue(value);
			cache.setExpire(expire);
			this.dao.insert(cache);
		}else{
			cache.setKey(key);
			cache.setValue(value);
			cache.setExpire(expire);
			this.dao.update(cache);
		}
	}

	@Override
	public void delCache(String key) {
		Cache cache = getCache(key);
		if(cache != null){
			this.dao.remove(cache.getId());
		}
	}
}
